<template>
  <lb-layout
    class="alarmList"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      pagination
      background
      border
      height="600"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
      class="addCourseTypeTable"
    >
      <!-- @selection-change="handleSelectionChange" -->
    </lb-table>
    <alarmPop :visible.sync="show" :resuestP="resuestP"></alarmPop>
  </lb-layout>
</template>

<script>
import { postTotalalarm, postTotalwateralarm } from "@/api/iot/inspect";
import { formatDate } from "@/utils/index";
import alarmPop from "@/views/maintenance/realtime/inspect/components/alarmPop.vue";
import CascaderSelect from "@/components/Select/CascaderSelect";
import RemoteSelect from "@/components/Select/RemoteSelect";

export default {
  name: "alarmList",
  dicts: [
    "device_alarm_type", // 设备警报类型
    "device_model", // 设备型号
    "wmeter_device_model", // 水表型号
  ],
  components: {
    alarmPop,
    RemoteSelect,
    CascaderSelect,
  },
  data() {
    return {
      show: false,
      resuestP: {},
      extraParams: {},
      netwoekChose: null,
      dictArr: [],
      apsForm: {
        formRef: "form",
        labelWidth: "100px",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            // bsColumn: {
            //   col: 3,
            // },
            size: "small",
          },
          properties: {
            startAndend: {
              label: "事件时间:",
              typeName: "el-date-picker",
              type: "datetimerange",
              size: "small",
              "start-placeholder": "开始时间",
              "end-placeholder": "结束时间",
              "value-format": "timestamp",
            },
            sysDeptId: {
              label: "用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let valNum = that.$refs?.form?.getFieldsValue().sysDeptId;
                return (
                  <div>
                    <CascaderSelect
                      value={valNum}
                      values={valNum}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择用能单位"}
                      filterable={true}
                      onInput={that.handlerLiandong}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            monitoringNetworkId: {
              label: "能耗终端:",
              typeName: "el-select",
              render: () => {
                let that = this;
                return (
                  <div>
                    <RemoteSelect
                      v-model={that.netwoekChose}
                      varient="networks"
                      extraParams={that.extraParams}
                      placeholder={"请选择能耗终端"}
                      size={"small"}
                      onInput={that.choseNetwork}
                    ></RemoteSelect>
                  </div>
                );
              },
            },
            deviceModel: {
              label: "设备型号:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dictArr.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().deviceModel;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择设备型号",
                        value: valNum,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("deviceModel", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            alarmType: {
              label: "警报类型:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict.type.device_alarm_type.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().alarmType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择警报类型",
                        value: valNum,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("alarmType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            cardNum: {
              label: "通信网卡号:",
              typeName: "el-input",
              placeholder: "请输入通信网卡号",
            },
            deviceCode: {
              label: "设备编号:",
              typeName: "el-input",
              placeholder: "请输入设备编号",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            // {
            //   label: "返回",
            //   typeName: "el-button",
            //   size: "small",
            //   icon: "el-icon-back",
            //   click: this.handleGoback,
            // },
          ],
        },
      },
      tableData: {
        column: [
          // {
          //   type: "selection",
          // },
          {
            prop: "name",
            label: "能耗终端",
            showOverflowTooltip: true,
          },
          {
            prop: "cardNum",
            label: "通信网卡号",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceName",
            label: "设备名称",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceCode",
            label: "设备编号",
            showOverflowTooltip: true,
          },
          {
            prop: "deviceModel",
            align: "center",
            label: "设备类型",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={
                      this.alarmListtype == "1"
                        ? this.dict.type.device_model
                        : this.dict.type.wmeter_device_model
                    }
                    value={scope.row.deviceModel}
                  />
                </div>
              );
            },
          },
          {
            prop: "alarmType",
            align: "center",
            label: "警报类型",
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.device_alarm_type}
                    value={scope.row.alarmType}
                  />
                </div>
              );
            },
          },
          {
            prop: "eventTime",
            align: "center",
            label: "事件时间",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let a = formatDate(scope.row.eventTime);
              return h(
                "div",
                {
                  style: {
                    color: "#000000",
                  },
                },
                a
              );
            },
          },
          {
            label: "操作",
            width: "150",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let text = that.premiText;
              let a = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-hasPermi={[text]}
                  onClick={() => {
                    that.resuestP = {
                      deviceCode: scope?.row?.deviceCode ?? "",
                      startTime: scope?.row?.startTime ?? "",
                      endTime: scope?.row?.endTime ?? null,
                      deviceModel: scope?.row?.deviceModel ?? "",
                      type: that.alarmListtype,
                    };
                    setTimeout(() => {
                      that.show = true;
                    }, 100);
                  }}
                >
                  详情
                </el-button>
              );
              return <div>{a}</div>;
            },
          },
        ],
        data: [],
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      alarmListtype: null, // 列表类型 1：电表 2：水表
      // multipleSelection: [],
      premiText: "",
    };
  },
  created() {
    // this.typeJudge();
    this.routerJudge();
  },
  mounted() {
    this.initData();
  },
  methods: {
    routerJudge() {
      let routeflage = this.$route.path;
      switch (routeflage) {
        case "/maintenance/realtime/inspect":
          this.alarmListtype = "1";
          this.dictArr = this.dict.type.device_model;
          this.premiText = "device:emeter:list";
          break;
        case "/maintenance/realtime/inspect2":
          this.alarmListtype = "2";
          this.dictArr = this.dict.type.wmeter_device_model;
          this.premiText = "device:wmeter:list";
          break;
      }
    },
    // typeJudge() {
    //   // this.alarmListtype = this.$route.query.type;
    //   // switch (this.alarmListtype) {
    //   //   case "1":
    //   //     this.dictArr = this.dict.type.device_model;
    //   //     break;
    //   //   case "2":
    //   //     this.dictArr = this.dict.type.wmeter_device_model;
    //   //     break;
    //   // }
    // },
    // 联动
    handlerLiandong(value) {
      this.netwoekChose = null;
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      this.$refs?.form?.setFieldValue("sysDeptId", result);
      // 请求能耗终端
      this.extraParams = {
        sysDeptId: result,
      };
    },
    /* 选择能耗终端 */
    choseNetwork(value) {
      this.netwoekChose = value;
    },
    initData(currentPage, pageSize, data) {
      let that = this;
      let query = {};
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      if (data) {
        query.sysDeptId = data?.sysDeptId ?? null;
        query.monitoringNetworkId = data?.monitoringNetworkId ?? null;
        query.deviceModel = data?.deviceModel ?? null;
        query.alarmType = data?.alarmType ?? null;
        query.cardNum = data?.cardNum ?? null;
        query.startTime = data?.startTime ?? null;
        query.endTime = data?.endTime ?? null;
        query.deviceCode = data?.deviceCode ?? null;
      }
      switch (this.alarmListtype) {
        case "1":
          this.postList1(query);
          break;
        case "2":
          this.postList2(query);
          break;
      }
    },
    // 电表
    postList1(query) {
      this.$store.commit("app/updateApiCount", "add");
      postTotalalarm(query)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.tableData.data = res?.rows ?? [];
          this.total = res?.total ?? 0;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!200098");
        });
    },
    // 水表
    postList2(query) {
      this.$store.commit("app/updateApiCount", "add");
      postTotalwateralarm(query)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.tableData.data = res?.rows ?? [];
          this.total = res?.total ?? 0;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!200099");
        });
    },
    handlerSearchDetail(val) {
      const { startAndend, ...other } = this.$refs?.form?.getFieldsValue();
      let data = { ...other };
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      if (startAndend) {
        data.startTime = startAndend[0];
        data.endTime = startAndend[1];
      }
      data.monitoringNetworkId = this.netwoekChose;
      data.deviceModel = this.$refs?.form?.getFieldsValue().deviceModel;
      data.alarmType = this.$refs?.form?.getFieldsValue().alarmType;
      data.cardNum = this.$refs?.form?.getFieldsValue().cardNum;
      data.deviceCode = this.$refs?.form?.getFieldsValue().deviceCode;
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      this.$refs?.form?.resetFields();
      this.netwoekChose = null;
      this.extraParams = {};
      this.handlerSearchDetail();
    },
    handleGoback() {
      let router;
      switch (this.alarmListtype) {
        case "1":
          router = "/maintenance/realtime/inspect";
          break;
        case "2":
          router = "/maintenance/realtime/inspect2";
          break;
      }
      this.$router.push({ path: router, query: {} }).catch(() => {});
    },
  },
};
</script>
<style scoped lang="scss">
.alarmList {
  width: 100%;
}
</style>

<!-- <template>
  <div class="inspect">
    <lb-layout
      v-loading="$store.getters.loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="#a19f9fb0;"
      :paddBottom="5"
    >
    </lb-layout>
  </div>
</template>

<script>
export default {
  name: "inspect",
  components: {},
  dicts: ["sys_normal_disable", "device_status", "subentry_type"],
  data() {
    return{

    }
  },
  created() {},
  mounted() {
  },
  methods: {

  },
};
</script>

<style scoped lang="scss">
.inspect {
  width: 100%;
}
</style> -->
